﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Microsoft.IT.Crm.Utility.CrmSolutionManager
{
    public class SolutionImporter : ISolutionImporter
    {
        private ServiceInformation ServiceInformation;
        protected XrmServiceHelper XrmServiceHelper;

        public SolutionImporter()
        {
            ServiceInformation = GenerateServiceInformation();
            XrmServiceHelper = new XrmServiceHelper(ServiceInformation);
        }

        private ServiceInformation GenerateServiceInformation()
        {
            return new ServiceInformation();
        }

        public void Import()
        {
            var files = GetSolutionsFromFolder();
            if (files != null)
                foreach (var file in files)
                {
                    try
                    {
                        var bytes = File.ReadAllBytes(file);
                        XrmSolutionService.ImportSolution(bytes);
                        EnterpriseLibLogger.Log(string.Format("Solution:{0} imported.", Path.GetFileNameWithoutExtension(file)));
                    }
                    catch (Exception e)
                    {
                        EnterpriseLibLogger.Log(string.Format("Error: {0}", e.Message));
                    }
                }
        }

        private string[] GetSolutionsFromFolder()
        {
            var solutionFolder = Path.Combine(Environment.CurrentDirectory, CRMSolutionManagerConfig.Instance.SolutionFolder);
            if (Directory.Exists(solutionFolder))
            {
                var files = Directory.GetFiles(solutionFolder, string.Format("*{0}*.zip", CRMSolutionManagerConfig.Instance.SolutionFilter));
                return files;
            }

            return null;
        }
    }
}
